/*
    处理日记数据的逻辑
*/
const { sqlQuery } = require('../mysql/index')

const { StringDecoder } = require('string_decoder');
const decoder = new StringDecoder('utf8');

module.exports = {
    getDiaryList, getDiary, addDiary, updateDiary
}

//获取所有日记列表（仅获取日期和id）
async function getDiaryList() {
    let sql = `select id,date from diary_data;`
    return new Promise(function (resolve, reject) {
        sqlQuery(sql, (data) => {
            resolve(data)
        })
    })
}

//根据id获取日记信息
async function getDiary(id) {
    let sql = `select * from diary_data where id=${id};`
    return new Promise(function (resolve, reject) {
        sqlQuery(sql, (data) => {
            data[0].content = decoder.write(data[0].content)
            resolve(data)
        })
    })
}

//添加日记
async function addDiary(msg) {
    let date = msg.date
    let content = msg.content

    let sql = `insert into diary_data(date,content) values ("${date}","${content}");`
    return new Promise(function (resolve, reject) {
        sqlQuery(sql, data => {
            resolve(data)
        })
    })

}

//修改日记
async function updateDiary(msg) {
    let id = msg.id;
    let date = msg.date;
    let content = msg.content

    let sql = `update diary_data set date="${date}",content="${content}" where id="${id}";`
    return new Promise(function (resolve, reject) {
        sqlQuery(sql, data => {
            resolve(data)
        })
    })
}